package com.mall.shopping.services.xdx;

import com.mall.shopping.IHomeService;
import com.mall.shopping.converter.PanelConvertor;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContent;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.HomePageResponse;
import com.mall.shopping.dto.PanelContentItemDto;
import com.mall.shopping.dto.PanelDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * xdx
 * 2020/12/21
 * 21:09
 */
@Service
@Component
@Slf4j
public class HomePageServiceImpl implements IHomeService {

    @Autowired
    PanelMapper panelMapper;
    @Autowired
    PanelConvertor panelConvertor;
    @Autowired
    PanelContentMapper panelContentMapper;
    @Autowired
    ItemMapper itemMapper;


    /**
     * 显示主页内容：使用了dto中的HomePageResponse
     * 查询table：panel + panel_content + ?商品信息？（根据product Id 查询）
     * @return
     */
    @Override
    public HomePageResponse homepage() {
        List<Panel> panels = panelMapper.selectAllPanels();
        Set set = new HashSet();
        Set<PanelDto> panelDtos = panelConvertor.convert2DTOs(new HashSet<>(panels));
        for (PanelDto panelDto : panelDtos) {
            Integer panelId = panelDto.getId();
            Example example = new Example(PanelContent.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("panelId",panelId);

            //某一panelId的所有panel content，要封装到List<>中
            List<PanelContent> panelContents = panelContentMapper.selectByExample(example);
            List<PanelContentItemDto> panelContentItemDtos = panelConvertor.convert(panelContents);
            for (PanelContentItemDto panelContentItemDto : panelContentItemDtos) {
                Long productId = panelContentItemDto.getProductId();
                Item item = itemMapper.selectById(productId);
                panelContentItemDto.setProductName(item.getTitle());
                //此处报空指针，应该是panelContentItemDto=null，panelConvertor可能没有生效
                //打印item=null，panel表里有脏数据，删除就不会打印出item=null
                panelContentItemDto.setSubTitle(item.getSellPoint());
                panelContentItemDto.setSalePrice(item.getPrice());


            }//panelContentItemDtos至此封装完
            panelDto.setPanelContentItems(panelContentItemDtos);


        }//至此，panelDto封装完

        HomePageResponse homePageResponse = new HomePageResponse();
        homePageResponse.setPanelContentItemDtos(panelDtos);
        return homePageResponse;

    }
}


















